<template>
<div class="docAdd">
  <el-row :gutter="20">
    <el-col :span="4">
      <el-input placeholder="始发地" v-model="docForm.docStart" clearable :disabled="true"></el-input>
    </el-col>
    <el-col :span="4">
      <el-cascader v-model="docForm.docEnd" placeholder="目的地" :options="allProvince" filterable :show-all-levels="false"></el-cascader>
    </el-col>
    <el-col :span="2" style="line-height:40px">
      开单员:
    </el-col>
    <el-col :span="3">
      <el-input v-model="docForm.empName" disabled></el-input>
    </el-col>
    <el-col :span="5">
      付款方式:
      <el-radio-group v-model="docForm.payment">
        <el-radio-button label="已付"></el-radio-button>
        <el-radio-button label="提付"></el-radio-button>
      </el-radio-group>
    </el-col>
    <el-col :span="5">
      交货方式:
      <el-radio-group v-model="docForm.delivery" @change="delChange">
        <el-radio-button label="自提"></el-radio-button>
        <el-radio-button label="送货"></el-radio-button>
      </el-radio-group>
      <el-drawer
          :visible.sync="drawer"
          :direction="direction" 
          :size="size">
          <div id="map" style="width:100%;height:500px"></div>
      </el-drawer>
    </el-col>
  </el-row>
  <el-row :gutter="20">
    <el-col :span="2" style="line-height:40px">
      <p>托运人:</p>
    </el-col>
    <el-col :span="4">
      <el-input placeholder="必填" v-model="docForm.sinpper" clearable></el-input>
    </el-col>
    <el-col :span="2" style="line-height:40px">
      <p>收货人:</p>
    </el-col>
    <el-col :span="4">
      <el-input placeholder="必填" v-model="docForm.consignee" clearable></el-input>
    </el-col>
    <el-col :span="2" style="line-height:40px">
      <p>送货地址:</p>
    </el-col>
    <el-col :span="10">
      <el-input placeholder="需送货时必填" v-model="docForm.deliveryAddr" clearable></el-input>
    </el-col>
  </el-row>
  <el-row :gutter="20">
    <el-col :span="2" style="line-height:40px">
      <p>托运人电话:</p>
    </el-col>
    <el-col :span="4">
      <el-input placeholder="必填" v-model="docForm.sinTel" clearable></el-input>
    </el-col>
    <el-col :span="2" style="line-height:40px">
      <p>收货人电话:</p>
    </el-col>
    <el-col :span="4">
      <el-input placeholder="必填" v-model="docForm.conTel" clearable></el-input>
    </el-col>
    <el-col :span="2" style="line-height:40px">
      <p>备注:</p>
    </el-col>
    <el-col :span="6">
      <el-input v-model="docForm.remark" clearable></el-input>
    </el-col>
    <el-col :span="2" style="line-height:40px">
      <p>基础送货费:</p>
    </el-col>
    <el-col :span="2">
      <el-input v-model="deliCost" clearable></el-input>
    </el-col>
  </el-row>
  <table class="cargoList">
    <thead>
      <tr>
        <td>名称</td>
        <td>包装</td>
        <td>数量</td>
        <td>总体积/m³</td>
        <td>总重量/kg</td>
        <td>总价值</td>
        <td>删除</td>
        <td>保价</td>
        <td>保价费</td>
      </tr>
    </thead>
    <tbody>
      <tr v-for="(cargo,index) in cargoData" :key="index">
        <td><input v-model="cargo.cargoName"></td>
        <td><input v-model="cargo.cargoPack"></td>
        <td><input v-model="cargo.num"></td>
        <td><input v-model="cargo.bulk"></td>
        <td><input v-model="cargo.weight"></td>
        <td><input v-model="cargo.price"></td>
        <td>
          <el-button type="primary" icon="el-icon-delete" size="mini" @click="delCargo(index)">删除</el-button>
        </td>
        <td :rowspan="cargoData.length" v-if="index ==0">
          <el-radio v-model="isSupport" label="true">是</el-radio>
          <el-radio v-model="isSupport" label="false">否</el-radio>
        </td>
        <td :rowspan="cargoData.length" v-if="index ==0">
          <input v-model="support" disabled>
        </td>
      </tr>
      <tr>
        <td colspan="5">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="addCargo">添加</el-button>
        </td>
        <td style="border-right:none">
          基础运费:
        </td>
        <td style="border-left:none">
          <input v-model="docForm.freight">
        </td>
        <td style="border-right:none">
          总运费:
        </td>
        <td style="border-left:none">
          <input v-model="totalCost" disabled>
        </td>
      </tr>
    </tbody>
  </table>
  <el-row :gutter="20">
    <el-col :span="2" :offset="9">
      <el-button type="primary" icon="el-icon-document-checked" @click="submitDocument">提交</el-button>
    </el-col>
    <el-col :span="2" :offset="1">
      <el-button type="info" icon="el-icon-document-delete" @click="clearInput">取消</el-button>
    </el-col>
  </el-row>
</div>
</template>
<script>
  import {addDocument} from 'network/document.js'
  import {getSiteByName} from 'network/site.js'
  import { MP } from '@/map.js' 

  let loginAccount = JSON.parse(sessionStorage.loginAccount)

  export default {
    data() {
      return {
        drawer: false,//地图面板
        direction: 'rtl',
        size: '800px',
        map: {},
        points: {},   //目的地坐标
        city: '',           //目的地城市
        distan: 0,  //送货距离
        isSupport: 'false', //会否保价
        //运单数据
        docForm: {
          empName: loginAccount.empName,
          empId: loginAccount.empId,
          docDate: new Date().toLocaleDateString(),
          docStart: loginAccount.sitetb.siteName, //起运地
          docEnd:'',  //目的地
          sinpper: '',  //托运人
          sinTel: '',   //托运人电话
          consignee: '',  //收货人
          conTel: '', //收货人电话
          payment: '已付', //付款方式:已付,到付
          delivery: '自提', //交货方式:自提,送货
          deliveryAddr: '', //送货地址
          deliCost: 0,  //送货费
          packCost: 0,  //包装费
          freight: 0, //基础运费
          remark: '', //备注信息
          state: '运转中',  //状态
          stateInfo: '',  //状态相关信息
        },
        //运单货物数据
        cargoData: [{cargoName: '', cargoPack: '', num: 0, weight: 0,bulk: 0, price: 0},
          {cargoName: '', cargoPack: '', num: 0, weight: 0,bulk: 0, price: 0}]
      };
    },
    computed: {
      //送货费
      deliCost() {
        let bulk = 0
        if(this.docForm.delivery == '送货') {
          for(let cargo of this.cargoData) {
            bulk += cargo.bulk*1
          }
        }
        return bulk*10+this.distan*5
      },
      docEnd() {
        return this.docForm.docEnd[3]
      },
      //获取目的地三级联动列表
      allProvince() {
        //创建4级列表数组
        let options = []
        //从vuex取出所有省市区
        //循环遍历省份
        this.$store.state.modules.proCityArea.province.forEach((pro,index) => {
          //循环把省份放进列表第一层
          options.push({label:pro.proName,children: []})
           //循环把省份的城市放进列表第二层
          pro.citys.forEach((city,ind) => {
            options[index].children.push({value:city.cityName,label:city.cityName,children: []})
            //循环把城市的地区放进列表第三层
            city.areas.forEach((area,i) => {
              options[index].children[ind].children.push({label:area.areaName,children: []})
              //循环把地区的站点放进列表第四层
              area.sitetbs.forEach((site) => {
                options[index].children[ind].children[i].children.push({value:site.siteName,label:site.siteName})
              })
            })
          })
        })
        return options
      },
      //保价费
      support() {
        let sup = 0
        if(this.isSupport == 'true') {
          for(let cargo of this.cargoData) {
            sup += cargo.price*1
          }
        }
        return sup = Math.ceil(sup*3/1000)
      },
      //总运费
      totalCost() {
        let total = 0
        if(this.isSupport == 'true') {
          total += this.support*1
        }
        total = total*1 + this.docForm.freight*1 + this.docForm.packCost*1 + this.deliCost*1
        return total
      }
    },
    methods: {
      //添加货物栏
      addCargo() {
        this.cargoData.push({cargoName: '', cargoPack: '', num: 0, weight: 0,bulk: 0, price: 0})
      },
      //删除货物栏
      delCargo(index) {
        this.cargoData.splice(index, 1)
      },
      //清除页面数据页面
      clearInput() {
        this.isSupport = "false"
        this.docForm = this.$options.data().docForm
        this.cargoData = this.$options.data().cargoData
        this.distan = 0
      },
      //提交运单给后台
      submitDocument() {
        let document = this.docForm
        let cargoList = []
        document.support = this.support
        document.totalCost = this.totalCost
        document.docEnd = this.docEnd
        document.deliCost = this.deliCost
        for(let cargo of this.cargoData) {
          if(cargo.num != 0) {
            cargoList.push(cargo)
          }
        }
        document.cargos = cargoList
        if(document.docEnd == '' || document.docEnd == null) {
          this.$message.error("请选择目的地");
          return false
        }
        addDocument(document).then(res => {
          if(res != "success") {
            this.$message.error(res);
          }else {
            this.$message({
              message: '添加成功',
              type: 'success'
            });
            this.clearInput()
            //更新当前网点所有运单列表
            this.$store.dispatch('setDocument',JSON.parse(sessionStorage.loginAccount).sitetb.siteName)
          }
        }).catch(err => {
          console.log(err)
        })
      },
      delChange(value) {
        if(value =="送货") {
          this.drawer = true
        }
      },
      mapClick(e) {
        let marker = new BMap.Marker(new BMap.Point(e.point.lng, e.point.lat));        // 创建标注    
        this.map.addOverlay(marker);
        this.distance(e.point.lng, e.point.lat)
      },
      distance(x,y) {
        // 纬度
        let lat1 = (Math.PI / 180) * this.points.lat;
        let lat2 = (Math.PI / 180) * y;
        // 经度
        let lon1 = (Math.PI / 180) * this.points.lng;
        let lon2 = (Math.PI / 180) * x;
        // 地球半径
        let R = 6371;
        // 两点间距离 km，如果想要米的话，结果*1000就可以了
        let d = Math.acos(Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1)) * R;
        this.distan = Math.ceil(d)
      }
    },
    updated(){
      const _this = "lyyOKkxVBYr8bLfmiAfSiShvK5pnZGV5"
      MP(_this).then(() => {
        if(this.docEnd!= '' && this.docEnd!= null) {
          getSiteByName(this.docEnd).then(res => {
            this.points = {
              lng: res.coordinate.substring(0,res.coordinate.indexOf(",")),
              lat: res.coordinate.substring(res.coordinate.indexOf(",")*1+1)
            }
            this.map = new BMap.Map("map");          // 创建地图实例 
            this.map.enableScrollWheelZoom();   //启用滚轮放大缩小，默认禁用
            this.map.enableContinuousZoom();
            this.map.addControl(new BMap.ScaleControl()); 
            let point = new BMap.Point(this.points.lng, this.points.lat);  // 创建点坐标 
            this.map.centerAndZoom(point, 15);
            var marker = new BMap.Marker(point);        // 创建标注    
            this.map.addOverlay(marker); 
            this.map.addEventListener("click",this.mapClick)     
            // 创建地址解析器实例     
            let myGeo = new BMap.Geocoder();   
            let map = this.map
            myGeo.getPoint(this.docForm.deliveryAddr, function(point){      
                if (point) {      
                    map.centerAndZoom(point, 16);      
                    map.addOverlay(new BMap.Marker(point)); 
                }      
            }, 
            this.docForm.docEnd[1]);
          })
        }
      }) 
    }
  }
</script>

<style scoped>
.docAdd{
  width: 100%;
  height: 100%;
}
.el-row{
  margin-bottom: 3%;
}
.cargoList{
  width: 100%;
  margin-bottom: 30px;
  border-collapse: collapse;
  text-align: center;
}
.cargoList td{
  border: 0.01em solid rgb(207, 215, 229);
  width: 11%;
  height: 35px;
  line-height: 30px;
  padding: 0 10px;
}
.cargoList td input{
  border:none;
  outline: none;
  text-align: center;
  width: 80%;
}
</style>
